// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  // 取出两个数组的相同元素
  getArrEqual(arr1, arr2) {
    const newArr = [];
    for (let i = 0; i < arr2.length; i++) {
      for (let j = 0; j < arr1.length; j++) {
        if (arr1[j] === arr2[i]) {
          newArr.push(arr1[j]);
        }
      }
    }
    return newArr;
  }
  // 取出两个数组的不同元素
  getArrDifference(arr1, arr2) {
    return arr1.concat(arr2).filter(function(v, i, arr) {
      return arr.indexOf(v) === arr.lastIndexOf(v);
    });
  }

  async goodslistAction() {
    const page = this.post();
    const pages = page.pages;
    const limits = page.limits;
    const search = page.search;
    const zt = page.zt;
    const shopid = this.shop_userinfo.departmentid;

    const data = await this.model('or_subject_config')
      .alias('scf')
      .field('scf.subjectid, ss.isdisable, s.name, s.number, sc.name as cname, b.name as bname, s.remarks, ss.nums, ss.price')
      .join('think_or_goods s on s.id=scf.subjectid')
      .join('think_or_shop_goods ss on ss.goodsid=scf.subjectid')
      .join('think_or_brand b on b.id=s.brandid')
      .join('think_or_subjectcategory sc on sc.id=s.categoryid')
      .where({ 'scf.departmentid': shopid, 'ss.isdisable': zt, 'scf.type': 1, 's.name|s.number': ['like', '%' + search + '%'] })
      .group('scf.subjectid')
      .page(pages, limits)
      .order('scf.id DESC')
      .countSelect();

    return this.json(data);
  }

  // 启用或停用产品
  async unstopAction() {
    const id = this.post('id');
    const status = this.post('status');
    const shopid = this.shop_userinfo.departmentid;

    const res = await this.model('or_shop_goods').where({ goodsid: id, shopid: shopid }).update({ isdisable: status });

    if (status * 1) {
      return res ? this.success('弃用成功') : this.fail('弃用失败');
    } else {
      return res ? this.success('启用成功') : this.fail('启用失败');
    }
  }

  // 获取机构产品品牌分类列表
  async getbrandsAction() {
    const shopid = this.shop_userinfo.departmentid;

    const orid = await this.model('or_department').where({ id: shopid }).getField('pid', true);

    const data = await this.model('or_brand').where({ departmentid: orid }).select();

    return this.json(data);
  }

  // 通过机构品牌获取品牌下的产品
  async querygoodsAction() {
    let cates = JSON.parse(this.post('cates'));

    const shopid = this.shop_userinfo.departmentid;

    const orid = await this.model('or_department').where({ id: shopid }).getField('pid', true);

    if (think.isEmpty(cates)) cates = [0];

    const list = await this.model('or_goods').where({ departmentid: orid, brandid: ['IN', cates], isdisabled: 0 }).select();

    const exist = await this.model('or_shop_goods').where({ shopid: shopid }).getField('goodsid');
    const exist2 = await this.model('or_subject_config').where({ departmentid: shopid, type: 1 }).group('subjectid').getField('subjectid');

    const data = {
      glist: list,
      exist: this.getArrEqual(exist2, exist)
    };
    return this.json(data);
  }

  // pull organization goods to shop
  async pullgoodsAction() {
    let flag = true;
    const data = JSON.parse(this.post('data'));
    const or_subsid = [];
    data.forEach((v) => {
      or_subsid.push(v.goodsid);
    });

    const shopid = this.shop_userinfo.departmentid;
    const orid = await this.model('or_department').where({ id: shopid }).getField('pid', true);
    // check pull subjects whether repeat in shop.
    const pulled_subs = await this.model('or_shop_goods').where({ shopid: shopid }).getField('goodsid');
    const pulled_subs2 = await this.model('or_subject_config').where({ departmentid: shopid, type: 1 }).group('subjectid').getField('subjectid');

    this.getArrEqual(pulled_subs, pulled_subs2).forEach((v) => {
      if (or_subsid.indexOf(v) !== -1) {
        flag = false;
        return this.fail('拉取的项目已经存在');
      }
    });

    if (flag) {
      const add_data = [];
      const add_data2 = [];

      const or_subsid2 = await this.model('or_shop_goods').where({ shopid: shopid, goodsid: ['IN', or_subsid] }).getField('goodsid');
      const or_subsid3 = this.getArrDifference(or_subsid, or_subsid2);

      const or_sub_list = await this.model('or_subject_config').where({ type: 1, departmentid: orid, subjectid: ['IN', or_subsid] }).select();
      or_sub_list.forEach((v) => {
        add_data.push({
          subjectid: v.subjectid,
          subjectchildclassid: v.subjectchildclassid,
          type: 1,
          departmentid: shopid,
          // xjyjtype: v.xjyjtype,
          xjyjpercent: v.xjyjpercent,
          // xjyjfixed: v.xjyjfixed,
          xjtctype: v.xjtctype,
          xjtcpercent: v.xjtcpercent,
          xjtcfixed: v.xjtcfixed,
          // khyjtype: v.khyjtype,
          khyjpercent: v.khyjpercent,
          // khyjfixed: v.khyjfixed,
          khtctype: v.khtctype,
          khtcpercent: v.khtcpercent,
          khtcfixed: v.khtcfixed
          // minuscost: v.minuscost
        });
      });
      if (or_subsid3.length !== 0) {
        data.forEach((v) => {
          add_data2.push({
            goodsid: v.goodsid,
            shopid: shopid,
            price: v.price,
            nums: v.nums
          });
        });
      }

      const model = this.model('or_shop_goods');
      if (add_data.length !== 0) {
        if (add_data2.length !== 0) {
          await model.transaction(async() => {
            try {
              const res1 = await model.addMany(add_data2);
              const res2 = await this.model('or_subject_config').db(model.db()).addMany(add_data);
              if (res1 && res2) {
                await model.commit();
                return this.success('拉取成功!');
              } else {
                await model.rollback();
                return this.fail('拉取失败');
              }
            } catch (e) {
              await model.rollback();
              return this.fail('拉取失败！');
            }
          });
        } else {
          await model.transaction(async() => {
            try {
              const res = await this.model('or_subject_config').db(model.db()).addMany(add_data);
              if (res) {
                await model.commit();
                return this.success('拉取成功!');
              } else {
                await model.rollback();
                return this.fail('拉取失败');
              }
            } catch (e) {
              await model.rollback();
              return this.fail('拉取失败！');
            }
          });
        }
      } else {
        return this.fail('请先配置好机构产品的业绩和提成信息!');
      }
    }
  }

  // edit shop goods
  async editgoodsAction() {
    let flag = true;

    const subInfo = this.post().subInfo;
    const subConfig = this.post().subConfig;
    const shopid = this.shop_userinfo.departmentid;

    const insertsub = [];
    const updatesub = [];
    const reducesub = [];
    const subconfclassidlists = [];

    const getFieldata = await this.model('or_subject_config').where({ subjectid: subInfo.id, type: 1, departmentid: shopid }).getField('subjectchildclassid,id');
    const subconflists = getFieldata.subjectchildclassid;
    const subconfidlists = getFieldata.id;
    subConfig.forEach((v) => {
      subconfclassidlists.push(v.subjectchildclassid);
    });
    subConfig.forEach((v) => {
      if (subconflists.includes(v.subjectchildclassid)) {
        delete (v['name']);
        v['id'] = subconfidlists[subconflists.indexOf(v.subjectchildclassid)];
        updatesub.push(v);
      } else {
        insertsub.push({
          subjectid: subInfo.id,
          subjectchildclassid: v.subjectchildclassid,
          type: 1,
          departmentid: shopid,
          // xjyjtype: v.xjyjtype,
          xjyjpercent: v.xjyjpercent,
          // xjyjfixed: v.xjyjfixed,
          xjtctype: v.xjtctype,
          xjtcpercent: v.xjtcpercent,
          xjtcfixed: v.xjtcfixed,
          // khyjtype: v.khyjtype,
          khyjpercent: v.khyjpercent,
          // khyjfixed: v.khyjfixed,
          khtctype: v.khtctype,
          khtcpercent: v.khtcpercent,
          khtcfixed: v.khtcfixed
          // minuscost: v.minuscost
        });
      }
    });
    subconflists.forEach((v) => {
      if (!subconfclassidlists.includes(v)) {
        reducesub.push(v);
      }
    });

    const model = this.model('or_subject_config');
    await model.transaction(async() => {
      try {
        const upsubIfnum = await this.model('or_shop_goods').db(model.db()).where({ goodsid: subInfo.id }).update({ price: subInfo.price, nums: subInfo.nums });
        if (insertsub.length !== 0) {
          const return1 = await model.addMany(insertsub);
          if (!return1) { flag = false };
        }
        if (updatesub.length !== 0) {
          const return2 = await model.updateMany(updatesub);
          if (!return2) { flag = false };
        }
        if (reducesub.length !== 0) {
          const return3 = await model.where({ subjectid: subInfo.id, subjectchildclassid: ['in', reducesub], type: 1, departmentid: shopid }).delete();
          if (!return3) { flag = false };
        }
        if (upsubIfnum && flag) {
          await model.commit();
          return this.success('更新成功!');
        } else {
          await model.rollback();
          return this.fail('更新失败!');
        }
      } catch (e) {
        await model.rollback();
        return this.fail('更新失败!');
      }
    });
  }

  // 添加/编辑自营产品
  async addeditAction() {
    const data = this.post();
    const subInfo = data.subInfo;
    const subConfig = data.subConfig;
    const shopid = this.shop_userinfo.departmentid;
    const departmentid = await this.model('or_department').where({ id: shopid }).getField('pid', true);
    const addtime = Math.round(new Date().valueOf() / 1000);

    // 判断产品名称是否重复
    const repeat = await this.model('or_goods').where('departmentid="' + departmentid + '" AND (name="' + subInfo.name + '" OR number="' + subInfo.number + '") AND id!="' + subInfo.id + '"').select();

    if (!think.isEmpty(repeat)) {
      return this.fail('名称或编号重复');
    }

    // if (data.tdtype == 1) {
    //   data.percent = Number(data.percent / 100).toFixed(2);
    //   data.fixed = 0;
    // } else {
    //   data.percent = 0;
    //   data.fixed = data.fixed;
    // }

    // if (data.khtdtype == 1) {
    //   data.khpercent = Number(data.khpercent / 100).toFixed(2);
    //   data.khfixed = 0;
    // } else {
    //   data.khpercent = 0;
    //   data.khfixed = data.khfixed;
    // }

    const model = this.model('or_goods');
    const addsubConfig = [];
    if (subInfo.id * 1) {
      // 编辑项目
      // const upd = await this.model('or_goods').update(data);
      // const shopData = {
      //   price: data.price,
      //   tdtype: data.tdtype,
      //   percent: data.percent,
      //   fixed: data.fixed,
      //   khtdtype: data.khtdtype,
      //   khpercent: data.khpercent,
      //   khfixed: data.khfixed
      // };
      // const resShop = await this.model('or_shop_goods').where({ goodsid: data.id, shopid: shopid }).update(shopData);
      // return resShop ? this.success('编辑成功') : this.fail('编辑失败');
      let flag = true;
      const insertsub = [];
      const updatesub = [];
      const reducesub = [];
      const subconfclassidlists = [];
      const getFieldata = await this.model('or_subject_config').where({ subjectid: subInfo.id, type: 1, departmentid: shopid }).getField('subjectchildclassid,id');
      const subconflists = getFieldata.subjectchildclassid;
      const subconfidlists = getFieldata.id;
      const shopData = {
        price: subInfo.price,
        nums: subInfo.nums
      };
      subConfig.forEach((v) => {
        subconfclassidlists.push(v.subjectchildclassid);
      });
      subConfig.forEach((v) => {
        if (subconflists.includes(v.subjectchildclassid)) {
          delete (v['name']);
          v['id'] = subconfidlists[subconflists.indexOf(v.subjectchildclassid)];
          updatesub.push(v);
        } else {
          insertsub.push({
            subjectid: subInfo.id,
            subjectchildclassid: v.subjectchildclassid,
            type: 1,
            departmentid: shopid,
            // xjyjtype: v.xjyjtype,
            xjyjpercent: v.xjyjpercent,
            // xjyjfixed: v.xjyjfixed,
            xjtctype: v.xjtctype,
            xjtcpercent: v.xjtcpercent,
            xjtcfixed: v.xjtcfixed,
            // khyjtype: v.khyjtype,
            khyjpercent: v.khyjpercent,
            // khyjfixed: v.khyjfixed,
            khtctype: v.khtctype,
            khtcpercent: v.khtcpercent,
            khtcfixed: v.khtcfixed
            // minuscost: v.minuscost
          });
        }
      });
      subconflists.forEach((v) => {
        if (!subconfclassidlists.includes(v)) {
          reducesub.push(v);
        }
      });
      await model.transaction(async() => {
        try {
          const upsubIfnum = await model.where({ id: subInfo.id }).update(subInfo);
          const resShop = await this.model('or_shop_goods').db(model.db()).where({ goodsid: subInfo.id, shopid: shopid }).update(shopData);
          if (insertsub.length !== 0) {
            const return1 = await this.model('or_subject_config').db(model.db()).addMany(insertsub);
            if (!return1) { flag = false };
          }
          if (updatesub.length !== 0) {
            const return2 = await this.model('or_subject_config').db(model.db()).updateMany(updatesub);
            if (!return2) { flag = false };
          }
          if (reducesub.length !== 0) {
            const return3 = await this.model('or_subject_config').db(model.db()).where({ subjectid: subInfo.id, subjectchildclassid: ['in', reducesub], type: 1, departmentid: shopid }).delete();
            if (!return3) { flag = false };
          }
          if (upsubIfnum && resShop && flag) {
            await model.commit();
            return this.success('更新成功!');
          } else {
            await model.rollback();
            return this.fail('更新失败!');
          }
        } catch (e) {
          await model.rollback();
          return this.fail('更新失败!');
        }
      });
    } else {
      // 新增项目
      // const add = {
      //   name: data.name,
      //   price: data.price,
      //   remarks: data.remarks,
      //   departmentid: departmentid,
      //   shopid: shopid,
      //   addtime: addtime,
      //   brandid: data.brandid,
      //   categoryid: data.categoryid,
      //   nums: 0, // 机构数量为零
      //   number: data.number,
      //   tdtype: data.tdtype,
      //   percent: data.percent,
      //   fixed: data.fixed,
      //   khtdtype: data.khtdtype,
      //   khpercent: data.khpercent,
      //   khfixed: data.khfixed
      // };
      // const res = await this.model('or_goods').add(add);
      // // 加入分店产品
      // const shopData = {
      //   goodsid: res,
      //   shopid: shopid,
      //   price: data.price,
      //   nums: data.nums,
      //   tdtype: data.tdtype,
      //   percent: data.percent,
      //   fixed: data.fixed,
      //   khtdtype: data.khtdtype,
      //   khpercent: data.khpercent,
      //   khfixed: data.khfixed,
      //   isshop: 1
      // };
      // const resShop = await this.model('or_shop_goods').add(shopData);
      const addsubInfo = {
        name: subInfo.name,
        price: subInfo.price,
        remarks: subInfo.remarks,
        departmentid: departmentid,
        shopid: shopid,
        addtime: addtime,
        brandid: subInfo.brandid,
        categoryid: subInfo.categoryid,
        nums: subInfo.nums,
        number: subInfo.number
      };
      await model.transaction(async() => {
        try {
          // 写入数据库
          const subjectid = await model.add(addsubInfo);
          // 加入分店产品
          const shopData = {
            goodsid: subjectid,
            shopid: shopid,
            price: subInfo.price,
            nums: subInfo.nums,
            isshop: 1
          };
          subConfig.forEach((v) => {
            addsubConfig.push({
              subjectid: subjectid,
              subjectchildclassid: v.subjectchildclassid,
              type: 1,
              departmentid: shopid,
              // xjyjtype: v.xjyjtype,
              xjyjpercent: v.xjyjpercent,
              // xjyjfixed: v.xjyjfixed,
              xjtctype: v.xjtctype,
              xjtcpercent: v.xjtcpercent,
              xjtcfixed: v.xjtcfixed,
              // khyjtype: v.khyjtype,
              khyjpercent: v.khyjpercent,
              // khyjfixed: v.khyjfixed,
              khtctype: v.khtctype,
              khtcpercent: v.khtcpercent,
              khtcfixed: v.khtcfixed
              // minuscost: v.minuscost
            });
          });
          // 写入数据库
          const resShop = await this.model('or_shop_goods').db(model.db()).add(shopData);
          const subjectconfigid = await this.model('or_subject_config').db(model.db()).addMany(addsubConfig);
          if (subjectid && resShop && subjectconfigid) {
            await model.commit();
            return this.success('添加成功!');
          } else {
            await model.rollback();
            return this.fail('添加失败!');
          }
        } catch (e) {
          await model.rollback();
          return this.fail('添加失败！');
        }
      });
    }
  }

  // 自营产品列表
  async productlistAction() {
    const page = this.get();
    const pages = page.pages;
    const limits = page.limits;
    const search = page.search;
    const zt = page.zt;
    const shopid = this.shop_userinfo.departmentid;

    const data = await this.model('or_shop_goods')
      .alias('sg')
      .field('sg.*, g.id, g.name, g.number, g.remarks, g.addtime, b.name as bname,c.name as cname')
      .join('`think_or_goods` g on g.id=sg.goodsid')
      .join('`think_or_brand` b on b.id=g.brandid')
      .join('`think_or_subjectcategory` c on c.id=g.categoryid')
      .page(pages, limits)
      .order('g.id DESC')
      .where({ 'sg.shopid': shopid, 'sg.isshop': 1, 'sg.isdisable': zt, 'g.name|g.number': ['like', '%' + search + '%'] })
      .countSelect();

    return this.json(data);
  }

  // 停用、启用产品
  async goodsstatusAction() {
    // 暂时只停用分店
    const id = this.post('id');
    const st = this.post('st');
    const shopid = this.shop_userinfo.departmentid;

    const res = await this.model('or_shop_goods').where({ goodsid: id, shopid: shopid }).update({ isdisable: st });
    if (st * 1) {
      return res ? this.success('停用成功') : this.fail('停用失败');
    } else {
      return res ? this.success('启用成功') : this.fail('启用失败');
    }
  }

  async getgoodsconfigAction() {
    const subjectid = this.post().subjectid;
    const shopid = this.shop_userinfo.departmentid;
    const data = await this.model('or_subject_config')
      .alias('sc')
      .field('sc.*,sl.name')
      .join('`think_or_subject_childclass` sl on sc.subjectchildclassid=sl.id')
      .where({ 'sc.subjectid': subjectid, 'sc.departmentid': shopid, 'sc.type': 1 })
      .select();

    return this.json(data);
  }

  async getgoodsChildClassAction() {
    const shopid = this.shop_userinfo.departmentid;
    const orid = await this.model('or_department').where({ id: shopid }).getField('pid', true);
    const info = await this.model('or_subject_childclass').where({ departmentid: orid, type: 1 }).select();
    return this.json(info);
  }
}
